package com.clickhouse_test.app.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.clickhouse_test.app.mapper.clickhouse", sqlSessionFactoryRef = "ClickhouseSqlSessionFactory")
public class Datasource_ClickhouseConfig {
    @Bean(name = "ClickhouseDatasource")
    @ConfigurationProperties(prefix = "spring.datasource.clickhouse")
    public DataSource getClickhouseDatasource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "ClickhouseSqlSessionFactory")
    public SqlSessionFactory ClickhouseSqlSessionFactory(@Qualifier("ClickhouseDatasource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //bean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/learn/*.xml"));
        return bean.getObject();
    }

    @Bean("ClickhouseSqlSessionTemplate")
    public SqlSessionTemplate ClickhouseSqlSessionTemplate(@Qualifier("ClickhouseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}